package com.example.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.example.service.UserService;
import com.example.domain.Result;
import com.example.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/index")
public class IndexController extends BaseController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result login(String username, String password, HttpSession session) {
        System.out.println(username);
        System.out.println("*****************************");
        System.out.println(password);
        User user = userService.selectByUsernameAndPassword(username, password);
        if (user == null) {

            return error("用户名或密码错误");
        }
        session.setAttribute("login", user);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", user.getUsername());
        jsonObject.put("nickName", user.getNickName());
        jsonObject.put("userId", user.getUserId());
        jsonObject.put("roleKey", user.getRoleKey());
        return success(jsonObject);
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    public Result register(User user) {
        if (StrUtil.isBlank(user.getUsername())) {
            return error("用户名不能为空");
        }
        User dbUser = userService.selectUserByUsername(user.getUsername());
        if (dbUser != null) {
            return error("用户名已存在");
        }
        user.setRoleKey("USER");
        this.userService.insertUser(user);
        return success();
    }
}
